* main analysis
*** OUTLINE ***
* prelims
* prepare data
* tables and figs
* closing
********************************************************************************
* prelims																	   
********************************************************************************
{
clear all
cap log close
set more off
set scheme s1color
}
********************************************************************************
* prepare data
********************************************************************************
{
* load analysis dataset
use "$data/analysis_dataset.dta", clear

* globals 
global exit sub ua exitempl exitlabor duration
global next lnwagediff durnextjob sep6mo next_tempcont industry_change

#d;
	global controls_interacted i.male i.highschool i.urban 
	i.family i.last_tempcontract 
	i.prov
	c.lnlastwage
	c.UIentit c.urate_prov_qstart c.urate_prov_qUIend c.var_urate_prov_qstart c.var_urate_prov_qUIend 
	c.lndurlastjob
;
#d cr

#d;
	global controls male highschool urban 
	family last_tempcontract
	lnlastwage
	UIentit urate_prov_qstart urate_prov_qUIend 
	var_urate_prov_qstart var_urate_prov_qUIend 
	lndurlastjob i.prov
;
#d cr

#d;
	global controls_rd male highschool urban 
	family last_tempcontract
	lnlastwage
	UIentit urate_prov_qstart urate_prov_qUIend 
	var_urate_prov_qstart var_urate_prov_qUIend 
	lndurlastjob
;
#d cr

#d;
	global samplerest if (male!=. & highschool!=. & urban!=. & var_urate_prov_qstart!=.
	& var_urate_prov_qUIend!=. & UIentit!=. & urate_prov_qstart!=. & urate_prov_qUIend!=. & lndurlastjob!=. 
	& prov!=. & family!=. & last_tempcontract !=. & lnlastwage!=.)
	;
#d cr

global options r cluster(ProvQuarter)

scalar ref2012 = mdy(7,15,2012)

* restrict sample
keep if sampleperiod == 1 & sampleage == 1
sort id u_entry_date
duplicates drop id, force

}
********************************************************************************
* Table 1 - main
********************************************************************************
{
	
local varstokeep 1.treat#1.after

	eststo clear 
	local varthx 24

	foreach outcome in $exit { 
		
eststo: reg `outcome' i.treat##i.after $samplerest , $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0  , format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "No"

eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest , $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
} 

#d;
esttab using "$tables/rev_dd_main_exits.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr


	eststo clear 
	local varthx 24

	foreach outcome in $next { 
		
eststo: reg `outcome' i.treat##i.after $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_main_other.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups( "$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Change Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr


}
********************************************************************************
* Tables 2 and B1 - heterogeneity 
********************************************************************************
{
	
cap drop treatafter
g treatafter = treat*after
local varstokeep treatafter

cap drop medwage
cap drop lowwage
egen medwage = median(lastwage)
g lowwage = (lastwage < medwage)

foreach cat in baseline ui0 uimiddle ui24 age_5455 age_5255 uiexh nouiexh female male noedu edu nofam fam wagelow wagehigh { 

	if "`cat'" == "baseline" {
		local cat_rest
		local cat_tit "Baseline"
	}
	else if "`cat'" == "ui0" {
		local cat_rest & UIentit == 0
		local cat_tit "No UI"
	}
	else if "`cat'" == "uimiddle" {
		local cat_rest & UIentit >= 1 & UIentit <= 23
		local cat_tit "Some UI"
	}
	else if "`cat'" == "ui24" {
		local cat_rest & UIentit == 24
		local cat_tit "Full UI"
	}
	else if "`cat'" == "age_5455" {
		#d;
		local cat_rest & 
		((age_uiendplus30 >= 53.5 & age_uiendplus30 < 54.5)|
		(age_uiendplus30 >= 55 & age_uiendplus30 < 56))
		;
		#d cr
		local cat_tit "54 vs 55"
	}
	else if "`cat'" == "age_5255" {
		#d;
		local cat_rest & 
		((age_uiendplus30 >= 52 & age_uiendplus30 < 53)|
		(age_uiendplus30 >= 55 & age_uiendplus30 < 56))
		;
		#d cr
		local cat_tit "52 vs 55"
	}
	else if "`cat'" == "uiexh" {
		local cat_rest & ((round(duration/30) >= UIentit) | (ua==1|sub==1))
		local cat_tit "Exhausts UI"
	}
	else if "`cat'" == "nouiexh" {
		local cat_rest & ((round(duration/30)  < UIentit) & (ua==0&sub==0))
		local cat_tit "Does not exhaust UI"
	}
	else if "`cat'" == "female" {
		local cat_rest & male == 0
		local cat_tit "Female"
	}
	else if "`cat'" == "male" {
		local cat_rest & male == 1
		local cat_tit "Male"
	}
	else if "`cat'" == "noedu" {
		local cat_rest & highschool == 0
		local cat_tit "No High School"
	}
	else if "`cat'" == "edu" {
		local cat_rest & highschool == 1
		local cat_tit "High School"
	}
	else if "`cat'" == "nofam" {
		local cat_rest & family == 0
		local cat_tit "No Family"
	}
	else if "`cat'" == "fam" {
		local cat_rest & family == 1
		local cat_tit "Family"
	}
	else if "`cat'" == "wagelow" {
		local cat_rest & lowwage == 1
		local cat_tit "Low Wage"
	}
	else if "`cat'" == "wagehigh" {
		local cat_rest & lowwage == 0
		local cat_tit "High Wage"
	}

	la var treatafter "`cat_tit'"
	
	eststo clear 
	local varthx 24

	foreach outcome in $exit {
	
eststo: reg `outcome' treatafter treat after $samplerest `cat_rest', $options
eststo: reg `outcome' treatafter treat after i.after##($controls_interacted) $samplerest `cat_rest', $options
	
		
	} 

#d;
esttab using "$tables/rev_dd_exits_het_`cat'.tex", replace fragment star(* .1 ** .05 *** .01)
		keep(`varstokeep')
		label varwidth(`varthx') wrap b(3) se 
		nonumbers nomtitles noobs nolines
		substitute([1em] )
		;
#d cr

	eststo clear 
	local varthx 24
	
foreach outcome in $next { 

	eststo: reg `outcome' treatafter treat after $samplerest `cat_rest', $options
	eststo: reg `outcome' treatafter treat after i.after##($controls_interacted) $samplerest `cat_rest', $options

		
} 

#d;
esttab using "$tables/rev_dd_other_het_`cat'.tex", replace fragment star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap b(3) se keep(`varstokeep')
		nonumbers nomtitles noobs nolines
		substitute([1em] )
		;
#d cr

}
 
}
********************************************************************************
* Table 3 - fiscal effects
********************************************************************************
{

preserve

keep $samplerest & totstatecontsavings !=. & tottaxes !=.  & (age_uiendplus30 > 52)
local varstokeep 1.treat#1.after

	*** PART 1 - UI/UA
	eststo clear 
	local varthx 24

	foreach outcome in totsub_amount totua_amount { 
	
eststo: reg `outcome' i.treat##i.after  $samplerest, $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & (after==0 & treat==1), format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No" 
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest, $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & (after==0 & treat==1), format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
}

#d;
esttab using "$tables/rev_dd_budget_part1.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(2) keep(`varstokeep')
		stats(mean Controls r2 N, fmt(2 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Spending in 52/55yo Sub" "Spending in Other UA", pattern(1 0 1 0 )
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		
;
#d cr

	*** PART 2 - CONTRIBUTIONS AND PENSIONS
	eststo clear 
	local varthx 24

	foreach outcome in totstatecontsavings tottaxes { 
		
eststo: reg `outcome' i.treat##i.after  $samplerest, $options
format `outcome' %9.2f 
		summ `outcome' if (after==0 & treat==1), format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No" 
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest, $options
format `outcome' %9.2f 
		summ `outcome' if (after==0 & treat==1), format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
		
} 

#d;
esttab using "$tables/rev_dd_budget_part2.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(2) keep(`varstokeep')
		stats(mean Controls r2 N, fmt(2 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Pension Contributions Savings" "Taxes Raised", pattern(1 0 1 0 )
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		
;
#d cr

	*** PART 3 - TOTAL EFFECT
	eststo clear 
	local varthx 24

	foreach outcome in totaleff { 
		
eststo: reg `outcome' i.treat##i.after  $samplerest, $options
format `outcome' %9.2f 
		summ `outcome' if (after==0 & treat==1), format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No" 
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest, $options
format `outcome' %9.2f 
		summ `outcome' if (after==0 & treat==1), format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_budget_part3.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(2) keep(`varstokeep')
		stats(mean Controls r2 N, fmt(2 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Total Savings", pattern(1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		
;
#d cr

restore

}
********************************************************************************
* Figures 2, A7, and A8 - pre-trends and ES
********************************************************************************
{

preserve

local quarterreform = qofd(ref2012)
local lb = `quarterreform'-4
local ub = `quarterreform'+3

foreach outcome in $exit $next { 

	foreach agecomp in all old young { 
				

	if "`agecomp'" == "old" { 
		local agerest & (age_uiendplus30>=53.5 & age_uiendplus30<=56 & (age_uiendplus30<54.5 | age_uiendplus30>=55))

	}
	else if "`agecomp'" == "all" { 
		local agerest & (age_uiendplus30>=52 & age_uiendplus30<58)

	}
	else if "`agecomp'" == "young" { 
		local agerest & ((age_uiendplus30>=52 & age_uiendplus30<53) | (age_uiendplus30>=55 | age_uiendplus30<56))
		
	}
	
	if "`outcome'" == "sub" {
		local ytit Prob of Receiving the 52/55yo Subsidy (relative to `rel')
		local tit "Receives 52/55yo Subsidy"
		local xlabel none
	}
	else if "`outcome'" == "ua" {
		local ytit Prob of Receiving Other UA (relative to `rel')
		local tit "Receives Other UA"
		local xlabel none
	}
	else if "`outcome'" == "exitempl" {
		local ytit Prob of Exiting to Employment (relative to `rel')
		local tit "Exits to Employment"
		local xlabel none
	}
	else if "`outcome'" == "exitlabor" {
		local ytit Prob of Exiting the Labor Force (relative to `rel')
		local tit "Exits Labor Force/Welfare"
		local xlabel none
	}
	else if "`outcome'" == "duration" {
		local ytit Non-Empl Duration (relative to `rel')
		local tit "Non-Emp Duration"
		local xlabel none
	}
	else if "`outcome'" == "lnwagediff" {
		local ytit Log(Wage Difference) (relative to `rel')
		local tit "{&Delta} Log(Wage)"
		local xlabel none
	}
	else if "`outcome'" == "next_tempcont" {
		local ytit Temporary Job (relative to `rel')
		local tit "Temporary Job"
		local xlabel `lb'(2)`ub'
	}
	else if "`outcome'" == "industry_change" {
		local ytit Change Industry (relative to `rel')
		local xlabel `lb'(2)`ub'
		local tit "Changes Industry"
	}
	else if "`outcome'" == "durnextjob" {
		local ytit Log(Tenure) (relative to `rel')
		local tit "Tenure"
		local xlabel `lb'(2)`ub'
	}
	else if "`outcome'" == "sep6mo" {
		local ytit Separation in 6months (relative to `rel')
		local tit "Separation in 6mo"
		local xlabel none
	}
	
	
reg `outcome' ib209.quarter_UIend##i.treat i.after##($controls_interacted) $samplerest & quarter_UIend<214 `agerest', $options
	
	cap drop t 
	cap drop ci_low
	cap drop ci_high
	cap drop coef
	gen ci_low = .
	gen ci_high = .
	gen coef = .
	
forval i = 206(1)213 {
	if `i'!=209 {

	replace ci_low = _b[`i'.quarter_UIend#1.treat] - 1.96*_se[`i'.quarter_UIend#1.treat] in `i'
    replace ci_high = _b[`i'.quarter_UIend#1.treat] + 1.96*_se[`i'.quarter_UIend#1.treat] in `i' 
    replace coef = _b[`i'.quarter_UIend#1.treat]  in `i'
	
	}
}

gen t = _n 
replace t = t-209 

replace coef=0 if t==0
replace t = t + `quarterreform'-1
replace t = . if coef == . 
format t %tq
local yl = -0.1
local step = 0.05
local yu = 0.2
local z = `quarterreform' - 0.5
	
#d;
twoway (sc coef t , mcolor(dkgreen*1))
	(rcap ci_low ci_high t, lcolor(dkgreen*1)),
	legend(off)
	graphregion(color(white)) bgcolor(white)
	xline(`z', lp(dash)) 
	ylab(#3, labsize(small) nogrid)
	xlab(`xlabel', gmin gmax labsize(small) nogrid) 
	xscale(range(`lb' `ub'))
	yline(0, lwidth(thin))
	xtit("", size(small))
	title("`tit'", size(small))
	saving("$figs/gph/rev_eventstudyTC_`outcome'_`agecomp'", replace)
;
#d cr

	} 
} 

foreach agecomp in all young old young { 
															   
#d;
	graph combine "$figs/gph/rev_eventstudyTC_sub_`agecomp'.gph" 
	"$figs/gph/rev_eventstudyTC_ua_`agecomp'.gph" 
	"$figs/gph/rev_eventstudyTC_exitempl_`agecomp'.gph" 
	"$figs/gph/rev_eventstudyTC_exitlabor_`agecomp'.gph"
	"$figs/gph/rev_eventstudyTC_duration_`agecomp'.gph" 
	"$figs/gph/rev_eventstudyTC_lnwagediff_`agecomp'.gph" 
	"$figs/gph/rev_eventstudyTC_durnextjob_`agecomp'.gph"
	"$figs/gph/rev_eventstudyTC_next_tempcont_`agecomp'.gph" 
	"$figs/gph/rev_eventstudyTC_industry_change_`agecomp'.gph", 
	graphregion(color(white)) scheme(s1mono)
;
#d cr
graph export "$figs/rev_eventstudyTC_`agecomp'.pdf", replace
	
} 

restore

}
********************************************************************************
* Figure A4 - UI entitlement						   
********************************************************************************
{

preserve

g group = 1 if (age_uiendplus30 >= 52 & age_uiendplus30 < 55)
replace group = 2 if (age_uiendplus30 >= 55 & age_uiendplus30 < 58)

sort group
contract group UIentit if !missing(group, UIentit)
egen _percent = pc(_freq), by(group)
separate _percent, by(group)

gen UIentit1 = UIentit + 0
gen UIentit2 = UIentit + 0.4

#d;
tw (bar _percent UIentit1 if group==1, barw(0.4) fcol(red) lcolor(none)) ||
	(bar _percent UIentit2 if group==2, barw(0.4) fcol(blue) lcolor(none)),
	xtit("Months of UI Entitlement", size(small))
	graphregion(color(white)) bgcolor(white)
	xlab(0(4)24, labsize(small))
	xlab(, labsize(small))
	ylab(, labsize(small))
	ytit("Density", size(small))
	legend(order(1 "Age 52-55" 2 "Age 55-58" ) size(small) rows(1) nobox) 
	;
;
#d cr

graph export "$figs/UIEntit_hist_2in1.pdf", replace

restore

}
********************************************************************************
* Figure A5 - UI/UA entitlements							   
********************************************************************************
{

preserve
	
** max UA
* base
g maxUAentit = 6

* Lack of Contribution Subsidy
replace maxUAentit = 0 if UIentit==0 & family==0 & floor(durlastjob/30)<3
replace maxUAentit = floor(durlastjob/30) if UIentit==0 & family==0 & floor(durlastjob/30)>=3
replace maxUAentit = 6 if UIentit==0 & family==0 & floor(durlastjob/30)>=3 & maxUAentit > 6
replace maxUAentit = 21 if UIentit==0 & family==1 & floor(durlastjob/30)>=6 

* UI Exhaustion Subsidy
replace maxUAentit = 6 if UIentit >= 4
replace maxUAentit = 24 if UIentit < 9 & family == 1
replace maxUAentit = 30 if UIentit >= 9 & family == 1

** 52/55yo Subsidy
replace maxUAentit = 999 if age_uiendplus30 >= 55
replace maxUAentit = 999 if age_uiendplus30 >= 52 & reldays < 0

** potential bridgers
g daysto55 = (55 - age_uiendplus30) * 360
g daysto52 = (52 - age_uiendplus30) * 360
cap drop months_bridge
g months_bridge = .
replace months_bridge = floor(daysto52/30) if age_uiendplus30 < 52 & reldays < 0
replace months_bridge = floor(daysto55/30) if age_uiendplus30 < 55 & reldays >= 0
cap drop canbridge_*
g canbridge_before = .
g canbridge_after = .
	* before 
replace canbridge_before = 0 if age_uiendplus30 < 52 & reldays < 0
replace canbridge_before = 1 if age_uiendplus30 < 52 & (maxUAentit * 30) > daysto52 & reldays < 0
	* after
replace canbridge_after = 0 if age_uiendplus30 < 55 & reldays >= 0
replace canbridge_after = 1 if age_uiendplus30 < 55 & (maxUAentit * 30) > daysto55 & reldays >= 0

** update max UA
replace maxUAentit = 999 if canbridge_before == 1 & reldays < 0
replace maxUAentit = 999 if canbridge_after == 1 & reldays >= 0

** total UI + UA
cap drop maxUIUA
g maxUIUA = UIentit + maxUAentit

** histograms
drop if reldays < 0
cap drop UIentit
rename maxUIUA UIentit

replace UIentit = 60 if UIentit >= 999 & UIentit!=.

g group = 1 if (age_uiendplus30 >= 52 & age_uiendplus30 < 54.5)
replace group = 2 if (age_uiendplus30 >= 55 & age_uiendplus30 < 58)
sort group
contract group UIentit if !missing(group, UIentit)
egen _percent = pc(_freq), by(group)
separate _percent, by(group)

gen UIentit1 = UIentit + 0

cap la drop uiua
la def uiua 60 "{&infin}"
la val UIentit1 uiua

#d;
tw (bar _percent UIentit1 if group==1, barw(1) fcol(red) lcolor(none)),
	xtit("Months of combined UI and UA entitlement (Age 52-55)", size(small))
	graphregion(color(white)) bgcolor(white)
	xlab(0(6)60, valuelabel labsize(small))
	xlab(, labsize(small))
	ylab(, labsize(small))
	ytit("Density", size(small))
	legend(order(1 "Age 52-55" 2 "Age 55-58" ) size(small) rows(1) nobox) 
	saving("$figs/gph/UIUAEntit_hist_treat_aft", replace)
	title("", size(small))
	;
;
#d cr
graph export "$figs/UIUAEntit_hist_treat_aft.pdf", replace

restore	

}
********************************************************************************
* Table A3 - summary stats															   
********************************************************************************
{
	
preserve

capture program drop sumtableref
program define sumtableref
	syntax , [file(str)]
	local size "\footnotesize"
	
g ua_sub = (ua==1 & sub==1)

la var sub "Receives 52/55yo Sub"
la var exitempl "Exits to Employment"
la var exitlabor "Exits Labor Force/Welfare"
la var industry_change "Changes Industry"
la var ua_sub "Subsidy after UA" 
la var duration "Non-empl Duration (Days)"
la var wagediff "Daily wage difference (EUR)"
la var lastwage "Last daily wage (EUR)"
la var durnextjob "Tenure (Next Job)"
la var sep6mo "Separation in 6mo"
la var next_tempcont "Temp Contract (Next Job)"
la var last_tempcont "Temp Contract (Last Job)"
la var censored "Spell is Censored"
la var UIentit "UI Entitlement (Months)"

	keep $samplerest

	local binary 
	
	local outcomes sub ua exitempl exitlabor censored ua_sub duration wagediff durnextjob sep6mo next_tempcont industry_change disability
	local controls male highschool family urban last_tempcont lastwage UIentit 
	
	g full      = treat!=. & after!=.
	g smpl1     = full & after==0 & treat==0
	g smpl2     = full & after==0 & treat==1
	g smpl3		= full & after==1 & treat==0
	g smpl4     = full & after==1 & treat==1
		
	local conditions  "full" "smpl1" "smpl2" "smpl3" "smpl4"    
	
	local colhead0 &   (1)      &   (2)     &   (3)        &    (4)         &    (5)         
	local colhead1 &   Full     & Control      & Treatment  & Control  & Treatment
	local colhead2 &   Sample   &  Before   & Before     & After & After   

	local cols : word count "`conditions'"
	local cols = `cols'+1

	writeln `file' "\begin{tabular}{l *{`=`cols'-1'}{c}} "		
	writeln `file' "\hline  "
	writeln `file' "\hline \\ [-5pt]  "
	writeln `file' " `colhead0'    \\"	
	writeln `file' " `colhead1'    \\"	
	writeln `file' " `colhead2'    \\"	
	local paneltitles ""Panel A: Outcomes" "Panel B: Indiv Characteristics" 
	local panels outcomes  controls 
	foreach panel in `panels'  {
		local ppos: list posof "`panel'" in local(panels)
		local paneltit: word `ppos' of `paneltitles'
		writeln `file' "\midrule"		
		writeln `file' "\multicolumn{`cols'}{l}{\textbf{`size'{`paneltit'}}} \\ "
		foreach v in ``panel'' {
			local vl : variable label `v'
			local linemean `vl' 
			local linesd
			foreach c in "`conditions'" {
				if "`c'"=="full" & (("`panel'"=="dwscontrols") | ("`=substr("`v'",1,2)'"=="lj")) {
					local linemean  `linemean' & 
					local linesd    `linesd'   & 
					continue
				}
				qui sum `v' if `c'
				sigdigits a2 `=r(mean)'
				local mean: disp `fmt' `=r(mean)'
				local linemean  `linemean' & `mean'
				sigdigits a2 `=r(sd)'
				local sd: disp `fmt' `=r(sd)'
				local linesd    `linesd'   &  `=cond(`sd'!=.,"(`=ltrim("`sd'")')","`sd'")' 
			}
			writeln `file' "`linemean' \\"
			if !inlist("`v'","`binary'") writeln `file' "`linesd'   \\"
		}	
	}
	writeln `file' "\midrule  "	
	local j 1
	local countline 
	foreach c in "`conditions'" {
		count if `c'
		local count`j' = r(N)
		local countline `countline' & `count`j++''
	}
	writeln `file' "Number of observations `countline' \\ "	
	writeln `file' "\hline "
	writeln `file' "\hline \\ [-1.5ex] "
	writeln `file' "\end{tabular}"

end 

cd "$tables"
tempfile f
sumtableref, file(`f') 
filefilter `f' rev_summstats.tex, from("[htbp]") to("[p]") replace

restore	
	
}
********************************************************************************
* Table A4 - DI and OLF
********************************************************************************
{

g cendate = u_entry_date + 30*50
g notworkafter50m = ((startnextemp > cendate | startnextemp == .) & exitlabor==1)

	*** Panel A
local varstokeep 1.treat#1.after

	eststo clear 
	local varthx 24

	foreach outcome in disability notworkafter50m {
		
eststo: reg `outcome' i.treat##i.after $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"

eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_main_di_olf.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups( "DI after unemployment" "Exits LF/Welfare and does not work again", pattern(1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr


	*** Panels B and C
la def treatyoung 1 "Age 52-53"
la def treatold 1 "Age 54-55"	
	
cap drop treatv
g treatv = treat

foreach cat in young old {
	
	if "`cat'" == "young" {
	
	#d;
	local ageres & 
	((age_uiendplus30 >= 52 & age_uiendplus30 < 53)|
	(age_uiendplus30 >= 55 & age_uiendplus30 < 56))
	;
	#d cr
	
	la val treatv treatyoung
	
	}
	else if "`cat'" == "old" {
	
	#d;
	local ageres & 
	((age_uiendplus30 >= 53.5 & age_uiendplus30 < 54.5)|
	(age_uiendplus30 >= 55 & age_uiendplus30 < 56))
	;
	#d cr
	
	la val treatv treatold
	
	}

local varstokeep 1.treatv#1.after

	eststo clear 
	local varthx 24

	foreach outcome in disability notworkafter50m {
		
eststo: reg `outcome' i.treatv##i.after $samplerest `ageres', $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treatv==1 & after==0 `ageres', format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"
		
eststo: reg `outcome' i.treatv##i.after i.after##($controls_interacted) $samplerest `ageres', $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treatv==1 & after==0 `ageres', format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_main_di_olf_`cat'.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups( "DI after unemployment" "Exits LF/Welfare and does not work again", pattern(1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

} 

}
********************************************************************************
* Table A5 - only individuals in UI in jul 2012
********************************************************************************
{
preserve

replace after = . if (u_entry_date>ref2012)
	
local varstokeep 1.treat#1.after
local addrest & (age_uiendplus30 > 52)

	eststo clear 
	local varthx 24

	foreach outcome in $exit { 
		
eststo: reg `outcome' i.treat##i.after $samplerest `addrest', $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0  `addrest', format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "No"
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest `addrest', $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 `addrest', format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
} 

#d;
esttab using "$tables/rev_dd_aftermodif_exits.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr


	eststo clear 
	local varthx 24

	foreach outcome in $next { 
		
eststo: reg `outcome' i.treat##i.after $samplerest `addrest', $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 `addrest', format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"

		eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest `addrest', $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 `addrest', format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_aftermodif_other.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups( "$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Change Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

restore
}
********************************************************************************
* Figure A9 - effects by UI exhaustion
********************************************************************************
{
	
local maxdur = 12
local mindur = 24
local plotmaxdur = 12

foreach exit in e o {

	if "`exit'" == "e" {
		local tit "Exits to Employment"
	}
	else if "`exit'" == "o" {
		local tit "Exits Labor Force/Welfare"
	}

cap drop ci_* coef_* t N*
gen t = _n 
replace t = _n-(`mindur'+1)


tempvar duration
gen `duration' = round(duration_to_`exit'/30)
tempvar durvar 
g `durvar' = `duration'-UIentit
gen ci_low_`exit' = .
gen ci_high_`exit' = .
gen coef_`exit' = .
gen N_`exit' = . 

forval dur = -`mindur'/`maxdur'{
	
	tempvar lhs 
	g `lhs' =  inrange(floor(`durvar'),`dur',`dur') & (censored==0) if `durvar'>=`dur'

	reg `lhs' i.treat##i.after i.after##($controls_interacted) $samplerest, $options

	replace ci_low_`exit' = _b[1.treat#1.after] - invttail(`e(df_r)',0.025)*_se[1.treat#1.after]  if t ==`dur'
	replace ci_high_`exit' = _b[1.treat#1.after] + invttail(`e(df_r)',0.025)*_se[1.treat#1.after]  if t ==`dur'
	replace coef_`exit' = _b[1.treat#1.after]	 if t ==`dur'
	replace N_`exit' = e(N)  if t == `dur'

}

local label "`:var label duration_to_`exit''"
#d;
	tw (rcap ci_low_`exit' ci_high_`exit' t if (t<=`plotmaxdur' & t>=-`mindur'), yline(0) lcolor(green*1)) 
	(sc coef_`exit' t if (t<=`plotmaxdur' & t>=-`mindur'), mcolor(dkgreen*1)), 
	xtitle("Month relative to UI exhaustion") ytitle("After x Age 52-55") 
	title(`tit') 
	xlabel(-`mindur'(2)`plotmaxdur') legend(off) xsize(10)
	;
#d cr
	
gr export "$figs/rev_DD_UIexhaustion_duration_to_`exit'`plotmaxdur'.pdf", replace

} 

}
********************************************************************************
* Figure A11 - dynamic selection
********************************************************************************
{
	
local maxdur = 12
local mindur = 24
local plotmaxdur = 12

foreach outcome in male highschool family last_tempcontract {

	if "`outcome'" == "male" {
		local tit "Male"
		local scale
	}
	else if "`outcome'" == "highschool" {
		local tit "High School"
	}
	else if "`outcome'" == "family" {
		local tit "Family"
	}
	else if "`outcome'" == "last_tempcontract" {
		local tit "Temporary Contract in Last Job"
	}


foreach exit in e {

cap drop ci_* coef_* t N*
cap drop t
gen t = _n 
replace t = _n-(24 + 1)

tempvar duration
gen `duration' = round(duration_to_`exit'/30)
tempvar durvar 
g `durvar' = `duration'-UIentit
gen ci_low_w = .
gen ci_high_w = .
gen coef_w = .
gen N_w = . 

forval dur = -24/`maxdur'{
tempvar lhs 
reg `outcome' i.treat##i.after $samplerest & `durvar'==`dur' `Rest', r

replace ci_low_w = _b[1.treat#1.after] - invttail(`e(df_r)',0.025)*_se[1.treat#1.after]  if t ==`dur'
replace ci_high_w = _b[1.treat#1.after] + invttail(`e(df_r)',0.025)*_se[1.treat#1.after]  if t ==`dur'
replace coef_w = _b[1.treat#1.after]	 if t ==`dur'
	   replace   N_w = e(N)  if t == `dur'

}

local label "`:var label duration_to_`exit''"

#d;
	tw (rcap ci_low_w ci_high_w t if t<=`plotmaxdur', yline(0, lc(red)) lcolor(green*1)) 
	(sc coef_w t if t<=`plotmaxdur', mcolor(dkgreen*1) ms(small)), 
	xtitle("Months relative to UI exhaustion", size(small)) 
	title(`tit', size(small)) 
	xlabel(-24(3)`plotmaxdur', labsize(small)) legend(off) xsize(10)
	ylab(#3, labsize(small))
	graphregion(color(white)) scheme(s1mono)
	saving("$figs/gph/rev_DD_hazard_UIexhaustion_`outcome'`plotmaxdur'", replace)
	;
#d cr
gr export "$figs/rev_DD_hazard_UIexhaustion_`outcome'`plotmaxdur'.pdf", replace

}
} 

#d;
	graph combine "$figs/gph/rev_DD_hazard_UIexhaustion_male12.gph" 
	"$figs/gph/rev_DD_hazard_UIexhaustion_highschool12.gph"
	"$figs/gph/rev_DD_hazard_UIexhaustion_family12.gph" 
	"$figs/gph/rev_DD_hazard_UIexhaustion_last_tempcontract12.gph", 
	graphregion(color(white)) scheme(s1mono)
;
#d cr
	graph export "$figs/rev_DD_hazards_DynamicSel.pdf", replace

}
********************************************************************************
* Figure A12 - OVB								   
********************************************************************************
{
** temp dataset
preserve
	clear
	set obs 20
	g comb = _n
	g rmax = 0.05 * comb
	g delta = .
	g beta = .
	save "$data/temp/store_coeff.dta", replace
restore
	
** estimate delta and adj beta
local varthx 24

cap drop treatXafter
g treatXafter = treat * after

reg lnwagediff treatXafter treat i.after##($controls_interacted) $samplerest, $options

forval j = 6(1)20 {
	local i = `j' / 20
	display "Loop: i=`i', j=`j'"
	
	* delta
	psacalc delta treatXafter, rmax(`i') beta(0) mcontrol(treat after)
		local delta_`j' = round(r(delta), .001)
		display "delta = `delta_`j'' - R_max = `i'"
	* adjusted beta
	psacalc beta treatXafter, rmax(`i') delta(1) mcontrol(treat after)
		local beta_`j' = round(r(beta), .001)
		display "beta = `beta_`j'' - R_max = `i'"
	* update temp dataset
		preserve
			use "$data/temp/store_coeff.dta", clear
			replace delta = `delta_`j'' if comb == `j'
			replace beta = `beta_`j'' if comb == `j'
			save "$data/temp/store_coeff.dta", replace
		restore
	}
	
** plot
preserve
use "$data/temp/store_coeff.dta", clear
local r_sq = 0.24

#delimit ;
	tw (connected delta rmax, lp(solid) lcolor(blue) ms(triangle) mc(blue)), 
	ytitle("Delta", size(small)) 
	xtitle("R_max", size(small))
	xlabel(0(0.1)1, angle(0) nogrid gmin gmax labsize(small))
	ylabel(-10(5)1, nogrid gmin gmax labsize(small))
	ylabel(,labsize(small))
	xline(`r_sq', lp(dash) lc(red))
	yline(0)
	graphregion(color(white)) bgcolor(white) 
	saving("$figs/gph/rev_wages_ovb_delta", replace)
	;
#d cr
graph export "$figs/rev_wages_ovb_delta.pdf", replace

** erase temporary files
cap erase "$data/temp/store_coeff.dta"
cap erase "$figs/temp/re-empl_wages_ovb_delta.gph"
cap erase "$figs/temp/re-empl_wages_ovb_beta.gph"
restore
}
********************************************************************************
* Table B7 - placebo
********************************************************************************
{
preserve

use "$data/analysis_dataset.dta", clear

drop after
g after = .
replace after = 1 if (ui_end_plus30>=mdy(7,15,2008) & ui_end_plus30<mdy(7,15,2009))
replace after = 0 if (ui_end_plus30>=mdy(7,15,2007) & ui_end_plus30<mdy(7,15,2008))
	
cap la drop after
label def after 1 "After" 0 "Before"
label val after after

keep if after!=. & sampleage == 1
sort id u_entry_date
duplicates drop id, force

local varstokeep 1.treat#1.after

	eststo clear 
	local varthx 24

	foreach outcome in $exit { 
		
eststo: reg `outcome' i.treat##i.after $samplerest , $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "No"
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest, $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
} 

#d;
esttab using "$tables/rev_dd_placebo_exits.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

	eststo clear 
	local varthx 24

	foreach outcome in $next { 
		
eststo: reg `outcome' i.treat##i.after $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"

eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_placebo_other.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups( "$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Changes Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

restore
}
********************************************************************************
* Table B9 - no family 2013
********************************************************************************
{
	
scalar ref2013 = mdy(3,17,2013)
g post_ref2013 = (ui_end_plus30>=ref2013)
g posref2013fam = post_ref2013 * family

local varstokeep 1.treat#1.after
local addrest & (age_uiendplus30 > 52) & posref2013fam!=1

	eststo clear 
	local varthx 24

	foreach outcome in $exit {
		
eststo: reg `outcome' i.treat##i.after $samplerest `addrest', $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0  `addrest', format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "No"

eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest `addrest', $options
		format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 `addrest', format
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
} 

#d;
esttab using "$tables/rev_dd_main_exits_nofam2013.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr


	eststo clear 
	local varthx 24

	foreach outcome in $next { 
		
eststo: reg `outcome' i.treat##i.after $samplerest `addrest', $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 `addrest', format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"
		
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest `addrest', $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 `addrest', format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_main_other_nofam2013.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(mean Controls r2 N, fmt(3 3 3 0) label("DV Mean (Pre-T)" "Controls" "R-sq" "Observations")) se
		mgroups( "$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Change Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}
********************************************************************************
* Figure B6 - donut size
********************************************************************************
{

forval d = 0(1)12 {

	local agepart = `d' / 12

	g treat_d`d' = (age_uiendplus30 >=52 & age_uiendplus30 <=55)
	replace treat_d`d' = . if (age_uiendplus30<52| age_uiendplus30>58) 
	replace treat_d`d' = . if (age_uiendplus30>=(55 - `agepart') & age_uiendplus30<55)

}

cap drop donut
g donut = .

foreach outcome in $exit $next { 

cap drop beta_`outcome'
cap drop se_`outcome' 

g beta_`outcome' = .
g se_`outcome' = .

forval d = 0(1)12 {


reg `outcome' i.after##i.treat_d`d' i.after##($controls_interacted) $samplerest , $options


replace donut = `d' if _n == `d' + 1
replace beta_`outcome' = _b[1.after#1.treat_d`d'] if _n == `d' + 1
replace se_`outcome' = _se[1.after#1.treat_d`d'] if _n ==`d' + 1

} 
} 

preserve

keep donut beta_* se_*
drop if donut == .

compress
save "$data/temp/donut_robustness", replace

g coef = .
g ci_low = .
g ci_high = .
g t = donut

foreach outcome in $exit $next  { 

	if "`outcome'" == "sub" {
		local tit "Receives 52/55yo Subsidy"
		local xtit
		local ylab 0(-0.1)-0.4
	}
	else if "`outcome'" == "ua" {
		local tit "Receives Other UA"
		local xtit
		local ylab 0(0.1)0.35
	}
	else if "`outcome'" == "exitempl" {
		local tit "Exits to Employment"
		local xtit
		local ylab 0(0.03)0.12
	}
	else if "`outcome'" == "exitlabor" {
		local tit "Exits Labor Force/Welfare"
		local xtit
		local ylab 0(0.03)0.12
	}
	else if "`outcome'" == "duration" {
		local tit "Non-Emp Duration"
		local xtit
		local ylab 0(-50)-200
	}
	else if "`outcome'" == "lnwagediff" {
		local tit "{&Delta} Log(Wage)"
		local xtit
		local ylab 0(-0.04)-0.16
	}
	else if "`outcome'" == "next_tempcont" {
		local tit "Temporary Job"
		local xtit "Donut Size (Months)"
		local ylab
	}
	else if "`outcome'" == "industry_change" {
		local tit "Changes Industry"
		local xtit "Donut Size (Months)"
		local ylab
	}
	else if "`outcome'" == "durnextjob" {
		local tit "Tenure"
		local xtit "Donut Size (Months)"
		local ylab
	}
	else if "`outcome'" == "sep6mo" {
		local tit "Separation in 6mo"
		local xtit
		local ylab
	}
	
replace coef = beta_`outcome'
replace ci_low = beta_`outcome' - 1.96 * se_`outcome'
replace ci_high = beta_`outcome' + 1.96 * se_`outcome'

#d;
twoway (rcap ci_low ci_high t if t!=6, lcolor(green*1))
	(sc coef t if t!=6, mcolor(dkgreen*1) )
	(rcap ci_low ci_high t if t==6, lcolor(blue*1) lp(dash)) 
	(sc coef t if t==6, mcolor(blue*1) ms(diamond)), 
	legend(off)
	graphregion(color(white)) bgcolor(white)
	ylab(`ylab', labsize(small) nogrid)
	xlab(0(1)12, gmin gmax angle(0) labsize(small) nogrid) 
	yline(0, lwidth(thin))
	xtit("`xtit'", size(small))
	title("`tit'", size(small))
	saving("$figs/gph/rev_donut_`outcome'", replace)
;
#d cr

} 

#d;
	graph combine "$figs/gph/rev_donut_sub.gph" 
	"$figs/gph/rev_donut_ua.gph" 
	"$figs/gph/rev_donut_exitempl.gph" 
	"$figs/gph/rev_donut_exitlabor.gph"
	"$figs/gph/rev_donut_duration.gph"
	"$figs/gph/rev_donut_lnwagediff.gph" 
	"$figs/gph/rev_donut_durnextjob.gph" 	
	"$figs/gph/rev_donut_next_tempcont.gph" 
	"$figs/gph/rev_donut_industry_change.gph", 
	graphregion(color(white)) scheme(s1mono)
;
#d cr
graph export "$figs/rev_donut_all.pdf", replace

restore

}
********************************************************************************
* Table B8 - additional wage r
********************************************************************************
{
	
** prelims
preserve
	
use "$data/analysis_dataset.dta", clear
keep id
duplicates drop id, force
merge 1:1 id using "$data/mcvl2004-17_03cont_rest_age_un_wide.dta", keepusing(cot72013 cot72014 cot72015 cot72016 cot72017)
keep if _merge == 3
drop _merge
save "$data/temp/temp_contributionjul2013.dta", replace

use "$data/int/analysis_dataset_spell.dta", clear

forval year = 2013(1)2017 {
	
	g t_worked`year' = (start < mdy(7,1,`year') & end >= mdy(7,30,`year') & state==1) 
	bys id: egen worked`year' = max(t_worked`year')
	drop t_worked`year'

}

keep id worked* 
duplicates drop id, force
compress
save "$data/temp/temp_workedjul.dta", replace

restore
	
** table
	** Panel A
g ptimeafter = (next_partialcoeff <= 0.75) & next_partialcoeff!=.
replace ptimeafter = . if exitempl == 0
replace next_partialcoeff = . if exitempl==0|lnwagediff==.

g lnwagediff_0unemp = lnwagediff
replace lnwagediff_0unemp = 0 if lnwagediff == .

	eststo clear 
	local varthx 24

foreach outcome in lnwagediff_0unemp ptimeafter { 
			
eststo: reg `outcome' i.treat##i.after  $samplerest , $options
format `outcome' %9.2f 
estadd local Controls "No"

eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest, $options
format `outcome' %9.2f 
estadd local Controls "Yes"
	
} 

#d;
esttab using "$tables/rev_dd_wagemisc.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(1.treat#1.after) nomtitles b(3)
		mgroups("$\Delta$ Log(Wage) ($\Delta$=0 if U)" "Part-time Job", pattern(1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		stats(N Controls , fmt(0 0) label("Observations" "Controls")) se
;
#d cr

	** Panel B 
merge 1:1 id using "$data/temp/temp_contributionjul2013.dta"
drop if _merge == 2
drop _merge 

merge 1:1 id using "$data/temp/temp_workedjul.dta"
drop if _merge==2
drop _merge

forval y = 2013(1)2017 {

	g left_u_jul`y' = (u_exit_date < mdy(7,1,`y'))
	g nextwage`y' = cot7`y'/100 if worked`y' == 1
	g lnwagediff`y' = ln(nextwage`y') - ln(lastwage)

}

cap g wagevar = .

	eststo clear 
	local varthx 24

	foreach year in 2013 2014 2015 2016 { 
	
	replace wagevar = lnwagediff`year'
		
eststo: reg wagevar i.treat##i.after i.after##($controls_interacted) $samplerest , $options
format wagevar %9.2f 
		summ wagevar $samplerest & treat==1 & after==0, format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Year "`year'"
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_futurewage.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(1.treat#1.after) nomtitles b(3)
		mgroups("$\Delta$ Log(Wage)", pattern(1 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
		stats(N Controls Year , fmt(0 0) label("Observations" "Controls" "Year")) se
;
#d cr

	** Panel C Lee bounds
cap drop medwage
egen medwage = median(lastwage)
cap drop lowwage
g lowwage = (lastwage < medwage)


	eststo clear 
	local varthx 24
	
eststo: leebounds lnwagediff treat $samplerest & after==1 & treat!=.
estadd local Tight
estadd local Wage "No"
estadd local Educ "No"
estadd local Cont "No"

eststo: leebounds lnwagediff treat $samplerest & after==1 & treat!=., tight(lowwage)
estadd local Wage "Yes"
estadd local Educ "No"
estadd local Cont "No"

eststo: leebounds lnwagediff treat $samplerest & after==1 & treat!=., tight(lowwage last_tempcontract)
estadd local Wage "Yes"
estadd local Educ "No"
estadd local Cont "Yes"

eststo: leebounds lnwagediff treat $samplerest & after==1 & treat!=., tight(lowwage last_tempcontract highschool)
estadd local Wage "Yes"
estadd local Educ "Yes"
estadd local Cont "Yes"


#d;
esttab using "$tables/rev_dd_leebounds.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap b(3)
		rename(lower "Lower Bound" upper "Upper Bound")
		substitute(treat )
		stats(N Tight Wage Cont Educ, fmt(0 0 0) label("Observations" "Tightening:" "Low Wage" "Last contract" "Education" )) se
		nomtitles
		mgroups("$\Delta$ Log(Wage)", pattern(1 0 0 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}
********************************************************************************
* Table B2 - paths
********************************************************************************
{

preserve	
	
g u_e = (exitempl==1 & ua==0 & sub==0)
g u_sub_e = (exitempl==1 & ua==0 & sub==1)
g u_ua_e = (exitempl==1 & ua==1 & sub==0)
g u_ua_sub_e = (exitempl==1 & ua==1 & sub==1)

g u_o = (exitlabor == 1 & ua==0 & sub==0)
g u_sub_o = (exitlabor==1 & ua==0 & sub==1)
g u_ua_o = (exitlabor==1 & ua==1 & sub==0)
g u_ua_sub_o = (exitlabor==1 & ua==1 & sub==1)

g u_c = (censored==1 & ua==0 & sub==0)
g u_sub_c = (censored==1 & ua==0 & sub==1)
g u_ua_c = (censored==1 & ua==1 & sub==0)
g u_ua_sub_c = (censored==1 & ua==1 & sub==1)

local varstokeep 1.treat#1.after

foreach exit in e o c {
	
		if "`exit'" == "e" {
			local tit "E"
			local addopts mean r2, fmt(3 3) label("DV Mean (Pre-T)" "R-sq")
		}
		else if "`exit'" == "o" {
			local tit "O"
			local addopts mean r2, fmt(3 3) label("DV Mean (Pre-T)" "R-sq")
		}
		else if "`exit'" == "c" {
			local tit "C"
			local addopts mean r2 Controls N, fmt(3 3 0 0) label("DV Mean (Pre-T)" "R-sq" "Controls" "Observations")
		}

	eststo clear 
	local varthx 24

	foreach outcome in u_`exit' u_sub_`exit' u_ua_`exit' u_ua_sub_`exit' { 
		
eststo: reg `outcome' i.treat##i.after $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "No"
eststo: reg `outcome' i.treat##i.after i.after##($controls_interacted) $samplerest , $options
format `outcome' %9.2f 
		summ `outcome' $samplerest & treat==1 & after==0 , format
		scalar mean = r(mean)
		estadd scalar mean
		estadd local Controls "Yes"
		
} 

#d;
esttab using "$tables/rev_dd_trans_`exit'.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap keep(`varstokeep') nomtitles b(3)
		stats(`addopts') se
		mgroups( "UI-`tit'" "UI-SUB-`tit'" "UI-UA-`tit'" "UI-UA-SUB-`tit'", pattern(1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
;
#d cr

}

restore

}
********************************************************************************
* Figures B2 and B5 - RDD mccrary
********************************************************************************
{

foreach group in 4952 5255 5558 {	
	
	if "`group'" == "4952" {
		local age_l = 49
		local age_u = 52
		local addtit
	} 
	else if "`group'" == "5255" {
		local age_l = 52
		local age_u = 55
		local addtit
	} 
	else if "`group'" == "5558" {
		local age_l = 55
		local age_u = 58
		local addtit "UI exhaustion date - July 15 2012"
	} 
	
local rdrest if age_uiendplus30 >= `age_l' & age_uiendplus30 < `age_u'

cap drop Xj Yj r0 fhat se_fhat
DCdensity reldays `rdrest', breakpoint(0) generate(Xj Yj r0 fhat se_fhat) nograph

local theta = round(`r(theta)', .001)
local theta_se = round(`r(se)', .001)
local size medsmall

local rest (Xj >= -365 & Xj <= 365)
local breakpoint 0
local cellmpname Xj
local cellvalname Yj
local evalname r0
local cellsmname fhat
local cellsmsename se_fhat
tempvar hi
quietly gen `hi' = `cellsmname' + 1.96*`cellsmsename'
tempvar lo
quietly gen `lo' = `cellsmname' - 1.96*`cellsmsename'
#d;
gr twoway (scatter `cellvalname' `cellmpname' if `rest', msymbol(circle_hollow) mcolor(gray)) 
(line `cellsmname' `evalname' if `evalname' < `breakpoint' , lcolor(black) lwidth(medthick)) 
(line `cellsmname' `evalname' if `evalname' > `breakpoint' & `rest', lcolor(black) lwidth(medthick)) 
(line `hi' `evalname' if `evalname' < `breakpoint' ,  lcolor(black) lwidth(vthin)) 
(line `lo' `evalname' if `evalname' < `breakpoint' , lcolor(black) lwidth(vthin)) 
(line `hi' `evalname' if `evalname' > `breakpoint' & `rest', lcolor(black) lwidth(vthin)) 
(line `lo' `evalname' if `evalname' > `breakpoint' & `rest', lcolor(black) lwidth(vthin)), 
xline(`breakpoint', lcolor(black)) legend(off) xscale(range(-365 365) noextend)
text(0.004 150 "Disc Est: `theta' (`theta_se')", place(se) just(left) size(`size'))
title("Age `age_l'-`age_u'", size(`size'))
ylab(0(0.001)0.005,labsize(`size'))
xlab(, labsize(`size'))
xtit("`addtit'", size(`size'))
saving("$figs/rdd_mccrary_`group'", replace) 
;
#d cr

graph export "$figs/rdd_mccrary_`group'.pdf", replace

}
}
********************************************************************************
* Figures B3 and B4 - RDD plots
********************************************************************************
{
	
foreach group in 5255 5558 {	
	
	if "`group'" == "5255" {
		local age_l = 52
		local age_u = 55
	} 
	else if "`group'" == "5558" {
		local age_l = 55
		local age_u = 58
	} 
	
	
local size small
local agerest & age_uiendplus30 >= `age_l' & age_uiendplus30 < `age_u'

foreach outcome in $exit $next { 

	if "`outcome'" == "sub" {
		local tit "Receives 52/55yo Subsidy"
		local addtit
	}
	else if "`outcome'" == "ua" {
		local tit "Receives Other UA"
		local addtit
	}
	else if "`outcome'" == "exitempl" {
		local tit "Exits to Employment"
		local addtit
	}
	else if "`outcome'" == "exitlabor" {
		local tit "Exits Labor Force/Welfare"
		local addtit
	}
	else if "`outcome'" == "duration" {
		local tit "Non-Emp Duration"
		local addtit
	}
	else if "`outcome'" == "lnwagediff" {
		local tit "{&Delta} Log(Wage)"
		local addtit
	}
	else if "`outcome'" == "next_tempcont" {
		local tit "Temporary Job"
		local addtit "UI exhaustion date - July 15 2012"
	}
	else if "`outcome'" == "industry_change" {
		local tit "Changes Industry"
		local addtit "UI exhaustion date - July 15 2012"
	}
	else if "`outcome'" == "durnextjob" {
		local tit "Tenure"
		local addtit "UI exhaustion date - July 15 2012"
	}
	else if "`outcome'" == "sep6mo" {
		local tit "Separation in 6mo"
		local addtit
	}

#d;
	rdplot `outcome' reldays $samplerest `agerest', 
	nbins(12 12) c(reldays)
	ci(95) shade
	graph_options(
	legend(off)
	ylab(#4,labsize(`size'))
	xlab(, labsize(`size'))
	xtit("`addtit'", size(`size'))
	title("`tit'", size(`size'))
	saving("$figs/gph/rdplot_`age_l'`age_u'_`outcome'", replace))
	;
#d cr

} 

* put plots together
#d;
	graph combine "$figs/gph/rdplot_`age_l'`age_u'_sub.gph" "$figs/gph/rdplot_`age_l'`age_u'_ua.gph" 
	"$figs/gph/rdplot_`age_l'`age_u'_exitempl.gph" "$figs/gph/rdplot_`age_l'`age_u'_exitlabor.gph"
	"$figs/gph/rdplot_`age_l'`age_u'_duration.gph"
	"$figs/gph/rdplot_`age_l'`age_u'_lnwagediff.gph" "$figs/gph/rdplot_`age_l'`age_u'_durnextjob.gph" 	
	"$figs/gph/rdplot_`age_l'`age_u'_next_tempcont.gph" "$figs/gph/rdplot_`age_l'`age_u'_industry_change.gph", 
	graphregion(color(white)) scheme(s1mono)
;
#d cr
graph export "$figs/rdplot_`age_l'`age_u'_all.pdf", replace

} 
}
********************************************************************************
* Table B3 - RDD					   
********************************************************************************
{

local treat_rest & (age_uiendplus30 >= 52 & age_uiendplus30 < 55)
local conto_rest & (age_uiendplus30 >= 55 & age_uiendplus30 < 58)

	eststo clear 
	local varthx 24

	foreach outcome in $exit { 

eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"

eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"
		
} 

#d;
esttab using "$tables/rev_rd_2groups_exits.tex", replace fragment booktabs
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( mean pv_rb h_r  N_h_l N_h_r Controls TR, fmt(3 3 2 0 0 0 0) 
		labels( "DV Mean (Pre)" "Robust p-value" "Bandwidth"  "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr

	eststo clear 
	local varthx 24

	foreach outcome in $next { 
		
eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"
		
eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"

} 


#d;
esttab using "$tables/rev_rd_2groups_other.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( mean pv_rb h_r N_h_l N_h_r Controls TR, fmt(3 3 2 0 0 0 0) 
		labels( "DV Mean (Pre)" "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Changes Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr

}
********************************************************************************
* Table B4 - RDD 1-year bw
********************************************************************************
{

local treat_rest & (age_uiendplus30 >= 52 & age_uiendplus30 < 55)
local conto_rest & (age_uiendplus30 >= 55 & age_uiendplus30 < 58)

	eststo clear 
	local varthx 24

	foreach outcome in $exit { 

eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd) vce(hc0) h(365) kernel(uniform)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"

eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0) h(365) kernel(uniform)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"
		
} 


#d;
esttab using "$tables/rev_rd_2groups_exits_1y_bw.tex", replace fragment booktabs
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( mean pv_rb h_r N_h_l N_h_r Controls TR, fmt(3 3 0 0 0 0 0) 
		labels( "DV Mean (Pre)" "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr

	eststo clear 
	local varthx 24

	foreach outcome in $next { 
		
eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd) vce(hc0) h(365) kernel(uniform)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"
		
eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0) h(365) kernel(uniform)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"

} 

#d;
esttab using "$tables/rev_rd_2groups_other_1y_bw.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( mean pv_rb h_r N_h_l N_h_r Controls TR, fmt(3 2 0 0 0 0) 
		labels( "DV Mean (Pre)" "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Changes Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr	
		
}
********************************************************************************
* Table B5 - RDD fiscal effects
********************************************************************************
{

preserve

keep $samplerest & totstatecontsavings !=. & tottaxes !=. 

rdrobust totaleff reldays $samplerest & (age_uiendplus30 >= 52 & age_uiendplus30 < 55), covs($controls_rd) vce(hc0) h(365) kernel(uniform)


local treat_rest & (age_uiendplus30 >= 52 & age_uiendplus30 < 55)
local conto_rest & (age_uiendplus30 >= 55 & age_uiendplus30 < 58)

	** PART 1 - UI/UA
	eststo clear 
	local varthx 24
	
	foreach outcome in totsub_amount totua_amount { 
	
eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest', format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"
		
eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest', format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"
		
} 


#d;
esttab using "$tables/rev_rd_budget_2g_part1.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( pv_rb h_r  N_h_l N_h_r Controls TR, fmt(3 2 0 0 0 0) 
		labels( "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("Spending in 52/55yo Sub" "Spending in Other UA", pattern(1 0 1 0 )
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr


	** PART 2 - CONTRIBUTIONS AND PENSIONS
	eststo clear 
	local varthx 24

	foreach outcome in totstatecontsavings tottaxes { 
		

eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest', format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"
		
eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest', format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"
		
} 


#d;
esttab using "$tables/rev_rd_budget_2g_part2.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( pv_rb h_r  N_h_l N_h_r Controls TR, fmt(3 2 0 0 0 0) 
		labels( "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("Pension Contributions Savings" "Taxes Raised", pattern(1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr

	*** PART 3 - TOTAL EFFECT
	eststo clear 
	
	local varthx 24

	foreach outcome in totaleff { 

eststo: rdrobust `outcome' reldays $samplerest `treat_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `treat_rest', format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "52-55"
		
eststo: rdrobust `outcome' reldays $samplerest `conto_rest', covs($controls_rd) vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conto_rest', format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar se = e(se_tau_rb)
		estadd scalar se
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "55-58"
		
} 


#d;
esttab using "$tables/rev_rd_budget_2g_part3.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( pv_rb h_r N_h_l N_h_r Controls TR, fmt(3 2 0 0 0 0) 
		labels( "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("Total Savings", pattern(1 0 )
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr

restore
	
}
********************************************************************************
* Table B6 - RDD young control
********************************************************************************
{

local conty_rest & (age_uiendplus30 >= 49 & age_uiendplus30 < 52)

	eststo clear 
	local varthx 24

	foreach outcome in $exit { 
			
eststo: rdrobust `outcome' reldays $samplerest `conty_rest', vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conty_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "No"
		estadd local TR "49-52"	
		
eststo: rdrobust `outcome' reldays $samplerest `conty_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conty_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "49-52"	
		
} 

#d;
esttab using "$tables/rev_rd_age4952_exits.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( mean pv_rb h_r N_h_l N_h_r Controls TR, fmt(3 3 2 0 0 0 0) 
		labels( "DV Mean (Pre)" "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("Receives 52/55yo Sub" "Receives Other UA" "Exits to Employment" "Exits Labor Force/Welfare" "Non-empl Duration", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr


	eststo clear 
	local varthx 24

	foreach outcome in $next { 
	
eststo: rdrobust `outcome' reldays $samplerest `conty_rest',  vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conty_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "No"
		estadd local TR "49-52"	

eststo: rdrobust `outcome' reldays $samplerest `conty_rest', covs($controls_rd)   vce(hc0)
		format `outcome' %9.2f 
		summ `outcome' $samplerest `conty_rest' & reldays < 0, format
		scalar EffN = e(N_h_l) + e(N_h_r)
		estadd scalar EffN
		scalar mean = r(mean)
		estadd scalar mean 
		estadd local Controls "Yes"
		estadd local TR "49-52"	
	

} 

#d;
esttab using "$tables/rev_rd_age4952_other.tex", replace fragment booktabs star(* .1 ** .05 *** .01)
		label varwidth(`varthx') wrap nomtitles b(3) se
		rename(RD_Estimate "After")
		stats( mean pv_rb h_r N_h_l N_h_r Controls TR, fmt(3 2 0 0 0 0) 
		labels( "DV Mean (Pre)" "Robust p-value" "Bandwidth" "Obs (Left)" "Obs (Right)" "Controls" "Age Group"))
		mgroups("$\Delta$ Log(Wage)" "Tenure" "Separation in 6mo" "Temporary Job" "Changes Industry", pattern(1 0 1 0 1 0 1 0 1 0)
		prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
	;
#d cr

}
********************************************************************************
* hazard prelims
********************************************************************************
{

* label exit vars 
gen u_to_e = exitempl 
gen u_to_o = exitlabor
gen u_to_ua = ua
gen u_to_subsidy = sub 
label var u_to_e "Exit to Employment" 
label var u_to_o "Exit Labor Force" 
label var u_to_ua "Exit to other UA" 
label var u_to_subsidy "Exit to Subsidy" 

foreach exit in e ua o sub {	
replace duration_to_`exit' = round(duration_to_`exit'/30)
label variable duration_to_`exit' "Months in Unemployment" 
}

save "$data/temp/analysis_dataset_hazards.dta", replace
}
********************************************************************************
* Figure 3 - hazards															   
********************************************************************************
{

** main program
timer clear
clear
set more off 

capture program drop main
program define main
	paths
	capture log close
	set trace on
	set tracedepth 2
	
	test_hazard

end 

** sub programs
* path macros
capture program drop paths
program define paths
	set trace off

	graph drop _all
	global figs  $figs
	global data  $data

	set trace on
end 

* hazards
capture program drop test_hazard
program define test_hazard
use "$data/temp/analysis_dataset_hazards.dta", replace

set scheme s1color

label var u_to_ua "Receives Other UA" 
label var u_to_subsidy "Receives 52/55yo Subsidy" 
label var u_to_e "Exits to Employment" 
label var u_to_o "Exits Labor Force/Welfare" 
label drop _all

g treat_haz = .
replace treat_haz = 1 if(age_uiendplus30 >= 52 & age_uiendplus30 < 54.5)
replace treat_haz = 0 if(age_uiendplus30 >= 55 & age_uiendplus30 < 58)
lab def treat_haz 1 "Treated (Age 52-55)" 0 "Control (Age 55-58)"
label val treat_haz treat_haz 
local forlab1: value label treat_haz
cap drop post
cap drop after

g after = .
replace after = 1 if (ui_end_plus30>=mdy(7,15,2012) & ui_end_plus30<mdy(7,15,2013))
replace after = 0 if (ui_end_plus30>=mdy(7,15,2011) & ui_end_plus30<mdy(7,15,2012))

g post = after
drop if post == . 

foreach exit in e ua o sub {	
 local lab3: var label u_to_`exit'
	di "`lab3'"
forval y=0(1)1{ 
local label1: label  `forlab1' `y'
	di "`label1'"
preserve 
keep if treat_haz == `y' 
hazard_by_group duration_to_`exit', byvar(post) exitvar(u_to_`exit') savefile(u_to_`exit'`y') title(`label1', size(medsmall)) 
restore 
}
grc1leg u_to_`exit'1.gph u_to_`exit'0.gph , ycommon rows(1) legendfrom(u_to_`exit'1.gph) title("`lab3'", size(small)) saving(u_to_`exit', replace)
graph export "$figs/rev_hazards_u_to_`exit'.pdf", replace
}
**#
grc1leg u_to_sub.gph u_to_ua.gph u_to_e.gph u_to_o.gph, legendfrom(u_to_e.gph) 
graph export "$figs/rev_hazards_u_to_allexits.pdf", replace

end 

* hazards pre/post
capture program drop hazard_by_group
program define hazard_by_group
	syntax varname, [ byvar(str) inclcens(integer 1) censorvar(varname) exitvar(varname)  controls(varlist) ///
		title(str) subtitle(passthru) ytitle(passthru) xtitle(passthru)  ///
		 ylabel(passthru) xlines(str) NOLEGEND scale(integer 1) ///
		 savefile(str) * ]
		 
tempfile filename
preserve
	
local durvar `varlist'
 local lab3: var label `exitvar'

local depvar hazard


local noci noci

qui tab post
	local N_unique = r(r)
	
	qui tab post, gen(__dby2_)
	local twogroups = `N_unique'==2
	
	forvalues i =1/`N_unique' {
		local byvardum `byvardum' __dby2_`i'
		local sebyvardum `sebyvardum' _se___dby2_`i'
		
		local Ngroups `Ngroups' N`i'
		
		local catlabel : variable label __dby2_`i'
		local catlabel = subinstr("`catlabel'","`byvar'==","",.)

		qui sum `N' if __dby2_`i'==1
		local max = r(max)
		local notes "`notes' "Number of obs, `catlabel':    `max'""
	
		if "`noci'"!="" {
			local graphs `graphs' ///
				(line `v' __dby2_`i' dur ,  lpattern("#") `msymbol') 
			local legendlabel `legendlabel' label(`i' "`catlabel'")
			local order `order' `i'
		}
		else {
			local graphs `graphs' ///
				(connected `v'hi __dby2_`i' , lpattern(shortdash) color(`col'*.6) msymbol(none) )  ///
				(connected `v'lo __dby2_`i' , lpattern(shortdash) color(`col'*.6) msymbol(none) )  ///
				(connected `v'   __dby2_`i' , lpattern("#") `msymbol' color(`col') )
			local legendlabel `legendlabel' label(`=`i'*3' "`catlabel'")
			local order `order' `=`i'*3'
		}
	
		gettoken col colors:colors
	}
	
	

count 
local N = r(N)

eststo clear 

local i 1 
tempname p
postfile `p' N dur pval `byvardum' `sebyvardum' `Ngroups' using `filename', replace
forval dur = 0(1)36 {

tempvar lhs
if strmatch("`depvar'","*hazard*") {
	if "`censorvar'"=="" {
					g `lhs' =  inrange(floor(`durvar'),`dur',`dur') & (`exitvar' == 1) if `durvar'>=`dur'	
				}
				else {

					g `lhs' =  inrange(floor(`durvar'),`dur',`dur') & (`censorvar'==0) & (`exitvar' == 1) if `durvar'>=`dur' 
				}	
			}
										local riskset `durvar'>=`dur'		

			
			if "`controls'"!="" foreach var of varlist `controls'  {
			qui sum `var' if `riskset'
			replace `var' = `var' - r(mean) if `riskset'
	}

	local tit : variable label `durvar'
			if "`tit'"=="" local tit `durvar' `label1' `label2'
		local poststr1
			local poststr2
			
			qui eststo : reg `lhs' `byvardum' `controls', noconstant 
			
			local pval .
			if `twogroups' == 1 {
				test __dby2_1==__dby2_2 
				local pval = r(p)
			}
			local Nobs
			foreach var in `byvardum' {
				local `var' = _b[`var']
				local _se_`var' = _se[`var']
				local poststr1 `poststr1' (``var'') 
				local poststr2 `poststr2' (`_se_`var'')
				count if e(sample) & `var'==1
				local Nobs `Nobs' (`=r(N)')
			}
		
			local obs = e(N)
			
			post `p' (`obs') (`dur') (`pval')  `poststr1' `poststr2' `Nobs'
			
			local i = `i'+1
			drop `lhs'
		}

		eststo clear				
		postclose `p'

		use `filename', clear
		
		if "`title'"=="" local title title("`lab3' Reform 2012") 
	else local title title(`title')
	
	if "`xtitle'"=="" local xtitle xtitle("Duration in Months")
	
	if "`xlines'"!="" local xline xline(`xlines', lpattern(dash) lwidth(*.6) lcolor(gs10))
	
	local statsig  
	if `twogroups' local statsig (rcap __dby2_1 __dby2_2 dur if pval<.05 & __dby2_1<=__dby2_2, lcolor(red) lwi(*1.9)) ///
			(rcap __dby2_1 __dby2_2 dur if pval<.05 & __dby2_1>__dby2_2 , lcolor(green) lwi(*1.9) lpa(dash)) 

	if "`nolegend'"=="" local legendlabel legend( `legendlabel' col(3))
	else local legendlabel legend(off)
	
	twoway `graphs' ///  
		`statsig' ///
		, scheme(s2color) graphr(color(white))  scale(.8) ysize(7) xsize(10) ///
		`title' `subtitle' ///
		`ytitle' `xtitle' ///
		`legendlabel' /// 
		legend(region(color(none) margin(zero)) order(`order') label(1 "Exhausts UI before Jul 2012") label(2 "Exhausts UI after Jul 2012") size(vsmall)) ///
		`xline'    `ylabel' `options' 
		graph save `savefile', replace 

graph export "$figs/`savefile'.pdf", replace
	
	

	restore
	
	end 

main

}
********************************************************************************
* Figure A6 - hazards: UI heterogeneity
********************************************************************************
{

** main program
timer clear
clear
set more off 

capture program drop main
program define main
	paths
	capture log close
	set trace on
	set tracedepth 2
	
	test_hazard

end // 

** sub programs
* define path macros
capture program drop paths
program define paths
	set trace off

	graph drop _all
	global figs  $figs
	global data  $data

	set trace on
end 

* hazards
capture program drop test_hazard
program define test_hazard
use "$data/temp/analysis_dataset_hazards.dta", clear
label var u_to_e "Exits to Employment" 
label var u_to_o "Exits Labor Force/Welfare" 
label drop _all

g treat_haz = .
replace treat_haz = 1 if(age_uiendplus30 >= 52 & age_uiendplus30 < 54.5)
replace treat_haz = 0 if(age_uiendplus30 >= 55 & age_uiendplus30 < 58)
lab def treat_haz  1 "Treated (Age 52-55)" 0 "Control (Age 55-58)"
label val treat_haz treat_haz 
local forlab1: value label treat_haz

cap drop post
cap drop after

g after = .
replace after = 1 if (ui_end_plus30>=mdy(7,15,2012) & ui_end_plus30<mdy(7,15,2013))
replace after = 0 if (ui_end_plus30>=mdy(7,15,2011) & ui_end_plus30<mdy(7,15,2012))

g post = after
drop if post == . 

foreach exit in e o {	
 local lab3: var label u_to_`exit'
	di "`lab3'"
forval y=0(1)1{
local label1: label  `forlab1' `y'
	di "`label1'"
preserve 
	keep if treat_haz == `y' 
	keep if UIentit == 24
	hazard_by_group duration_to_`exit', byvar(post) exitvar(u_to_`exit') savefile(u_to_`exit'`y'_24) title(`label1', size(medsmall))
restore

preserve
	keep if treat_haz == `y' 
	keep if UIentit == 0
	hazard_by_group duration_to_`exit', byvar(post) exitvar(u_to_`exit') savefile(u_to_`exit'`y'_0) title(`label1', size(medsmall))
restore 
}
* plots
grc1leg u_to_`exit'1_0.gph u_to_`exit'0_0.gph  , ycommon graphregion(color(white)) legendfrom(u_to_`exit'1_0.gph) title("`lab3' (No UI)", size(small)) rows(1) saving(u_to_`exit'_0, replace)
graph export "$figs/rev_hazards_u_to_`exit'_TC_0mo.pdf", replace
grc1leg u_to_`exit'1_24.gph u_to_`exit'0_24.gph , ycommon graphregion(color(white)) legendfrom(u_to_`exit'1_24.gph) title("`lab3' (Full UI)", size(small)) rows(1) saving(u_to_`exit'_24, replace)
graph export "$figs/rev_hazards_u_to_`exit'_TC_24mo.pdf", replace
}

* combine plots
grc1leg u_to_e_24.gph u_to_o_24.gph u_to_e_0.gph u_to_o_0.gph, graphregion(color(white)) legendfrom(u_to_e_0.gph) 
graph export "$figs/rev_hazards_u_to_allexits_TC_0_24mo.pdf", replace

end // 

* hazards pre/post
capture program drop hazard_by_group
program define hazard_by_group
	syntax varname, [ byvar(str) inclcens(integer 1) censorvar(varname) exitvar(varname)  controls(varlist) ///
		title(str) subtitle(passthru) ytitle(passthru) xtitle(passthru)  ///
		 ylabel(passthru) xlines(str) NOLEGEND scale(integer 1) ///
		 savefile(str) * ]
		 
tempfile filename
preserve
	
local durvar `varlist'
 local lab3: var label `exitvar'

local depvar hazard


local noci noci

qui tab post
	local N_unique = r(r)
	
	qui tab post, gen(__dby2_)
	local twogroups = `N_unique'==2
	
	forvalues i =1/`N_unique' {
		local byvardum `byvardum' __dby2_`i'
		local sebyvardum `sebyvardum' _se___dby2_`i'
		
		local Ngroups `Ngroups' N`i'
		
		local catlabel : variable label __dby2_`i'
		local catlabel = subinstr("`catlabel'","`byvar'==","",.)

		qui sum `N' if __dby2_`i'==1 
		local max = r(max)
		local notes "`notes' "Number of obs, `catlabel':    `max'""
	
		if "`noci'"!="" {
			local graphs `graphs' ///
				(line `v' __dby2_`i' dur ,  lpattern("#") `msymbol') // 
			local legendlabel `legendlabel' label(`i' "`catlabel'")
			local order `order' `i'
		}
		else {
			local graphs `graphs' ///
				(connected `v'hi __dby2_`i' , lpattern(shortdash) color(`col'*.6) msymbol(none) )  ///
				(connected `v'lo __dby2_`i' , lpattern(shortdash) color(`col'*.6) msymbol(none) )  ///
				(connected `v'   __dby2_`i' , lpattern("#") `msymbol' color(`col') )
			local legendlabel `legendlabel' label(`=`i'*3' "`catlabel'")
			local order `order' `=`i'*3'
		}
	
		gettoken col colors:colors
	}
	
	

count 
local N = r(N)

eststo clear 

local i 1 
tempname p
postfile `p' N dur pval `byvardum' `sebyvardum' `Ngroups' using `filename', replace
forval dur = 0(1)36 {

tempvar lhs
if strmatch("`depvar'","*hazard*") {
	if "`censorvar'"=="" {
					g `lhs' =  inrange(floor(`durvar'),`dur',`dur') & (`exitvar' == 1) if `durvar'>=`dur'	
				}
				else {

					g `lhs' =  inrange(floor(`durvar'),`dur',`dur') & (`censorvar'==0) & (`exitvar' == 1) if `durvar'>=`dur' 
				}	
			}
										local riskset `durvar'>=`dur'		

			
			if "`controls'"!="" foreach var of varlist `controls'  {
			qui sum `var' if `riskset'
			replace `var' = `var' - r(mean) if `riskset'
	}


	local tit : variable label `durvar'
			if "`tit'"=="" local tit `durvar' `label1' `label2'
		local poststr1
			local poststr2
			
			qui eststo : reg `lhs' `byvardum' `controls', noconstant 
			
			local pval .
			if `twogroups' == 1 {
				test __dby2_1==__dby2_2 
				local pval = r(p)
			}
			local Nobs
			foreach var in `byvardum' {
				local `var' = _b[`var']
				local _se_`var' = _se[`var']
				local poststr1 `poststr1' (``var'') 
				local poststr2 `poststr2' (`_se_`var'')
				count if e(sample) & `var'==1
				local Nobs `Nobs' (`=r(N)')
			}
		
			local obs = e(N)
			
			post `p' (`obs') (`dur') (`pval')  `poststr1' `poststr2' `Nobs'
			
			local i = `i'+1
			drop `lhs'
		}

		eststo clear				
		postclose `p'

		use `filename', clear
		
		if "`title'"=="" local title title("`lab3' Reform 2012") 
	else local title title(`title')
	
	if "`xtitle'"=="" local xtitle xtitle("Duration in Months")
	
	if "`xlines'"!="" local xline xline(`xlines', lpattern(dash) lwidth(*.6) lcolor(gs10))
	
	local statsig  
	if `twogroups' local statsig (rcap __dby2_1 __dby2_2 dur if pval<.05 & __dby2_1<=__dby2_2, lcolor(red) lwi(*1.9)) ///
			(rcap __dby2_1 __dby2_2 dur if pval<.05 & __dby2_1>__dby2_2 , lcolor(green) lwi(*1.9) lpa(dash)) 

	if "`nolegend'"=="" local legendlabel legend( `legendlabel' col(3))
	else local legendlabel legend(off)
	
	twoway `graphs' ///  
		`statsig' ///
		, scheme(s2color) graphr(color(white))  scale(.8) ysize(7) xsize(10) ///
		`title' `subtitle' ///
		`ytitle' `xtitle' ///
		`legendlabel' /// 
		legend(region(color(none) margin(zero)) order(`order') label(1 "Exhausts UI before Jul 2012") label(2 "Exhausts UI after Jul 2012") size(vsmall)) ///
		 `xline'    `ylabel' `options' xlabel(0(6)36)
		graph save `savefile', replace 

graph export "$figs/`savefile'.pdf", replace
	
	

	restore
	
	end // hazard_by_group

main

}
********************************************************************************
* Figure 1 - benefit profiles
********************************************************************************
{
	
* load benefit profiles
import excel "$orig/additional data/benefit profiles/ui_profiles.xlsx", sheet("Sheet1") firstrow clear

* convert rr to pct
replace rr_pre = rr_pre * 100
replace rr_post = rr_post * 100

* plot
#d ;
tw  (connected rr_pre t, connect(stairstep) lcolor(blue) ms(i) mc(blue) lw(thick))
	(connected rr_post t, connect(stairstep) lp(dash) lcolor(red) ms(i) mc(red) lw(thick)),
	graphregion(color(white)) bgcolor(white)
	ytitle("Replacement Rate (%)", size(medsmall))
	ylabel(0(20)100, nogrid gmin gmax labsize(medsmall))
	xtitle("Months in Unemployment", size(medsmall))
	xlabel(0(4)40, nogrid angle(0) labsize(medsmall))
	xline(25, lp(longdash_dot) lw(medium))
	legend(order(1 "Pre-2012 Reform" 2 "Post-2012 Reform") size(medsmall))
;
#d cr
graph export "$figs/b_profiles_general.pdf", replace

}
********************************************************************************
* Figure A2 - plot ui and ua series
********************************************************************************
{
* load data
use "$data/int/ui_ua_series.dta", clear
	
sort agroup year

* levels by U Benefit
#d ;
	tw (connected UI year if age=="Total", lp(blue) lcolor(blue) ms(triangle) mc(blue))
		(connected UA year if age=="Total", lp(red) lcolor(red) ms(square) mc(red)), 
	/*title("Total")*/
	ytitle("Recipients (1000s)", size(small)) 
	xtitle("Year", size(small))
	xlabel(2003(1)2017, angle(45) nogrid gmin gmax labsize(small))
	ylabel(500(250)1750, nogrid gmin gmax labsize(small))
	legend(order(1 "Contributive Level (UI)" 2 "Assistance Level (UA)") size(small))
	graphregion(color(white)) bgcolor(white) 
	;
#d cr
graph export "$figs/ui_ua_series_total.pdf", replace

* shares by U Benefit and Age Group
preserve
collapse UI_prop_agroup2 UA_prop_agroup2, by(year agroup2)
drop if agroup2==.
sort agroup2 year
#delimit ;
	tw (connected UI_prop_agroup2 year if agroup2==0, lp(solid) lcolor(blue) ms(triangle) mc(blue))
		(connected UA_prop_agroup2 year if agroup2==0, lp(dash) lcolor(red) ms(square) mc(red))
		(connected UI_prop_agroup2 year if agroup2==1, lp(solid) lcolor(blue) ms(triangle_hollow) mc(blue))
		(connected UA_prop_agroup2 year if agroup2==1, lp(dash) lcolor(red) ms(square_hollow) mc(red)), 
	ytitle("% over Active Population in Age Group", size(small)) 
	xtitle("Year", size(small))
	xlabel(2003(1)2017, angle(45) nogrid gmin gmax labsize(small))
	ylabel(0(5)45, nogrid labsize(small))
	legend(order(1 "Contributive Level (Age 35-49)" 2 "Assistance Level (Age 35-49)" 3 "Contributive Level (Age 50+)" 4 "Assistance Level (Age 50+)") size(small))
	graphregion(color(white)) bgcolor(white) 
	;
#d cr
restore
graph export "$figs/ui_ua_prop_series_byAggage.pdf", replace
	
}
********************************************************************************
* Figure A3 - Lit
********************************************************************************
{
	
* load data from NW
import excel "$orig/additional data/LittStata.xlsx", firstrow clear
destring ewg_sd extentioncutsizeinmonths, replace force
gen neg = 1 if p == "JM" | p == "DV"

foreach var of varlist ewg* eud* {
	replace `var' = `var'/extentioncutsizeinmonths

} 

g eud_c1 = eud-1.96*eud_sd
g eud_c2 = eud+1.96*eud_sd
g ewg_c1 = ewg-1.96*ewg_sd
g ewg_c2 = ewg+1.96*ewg_sd
g r=0

twoway ///
(rspike  ewg_c1 ewg_c2 eud if neg !=1, lc(dkgreen*1)) ///
(rspike  eud_c1 eud_c2 ewg if neg !=1, lc(dkgreen*1) hor) ///
(scatter ewg           eud if neg !=1, mlabel(p) mlabcolor(dkgreen*1) mcolor(dkgreen*1) mlabsize(vsmall) mlabposition(8) msize(small)) ///
(rspike  ewg_c1 ewg_c2 eud if neg ==1, lc(red) lp(dash)) ///
(rspike  eud_c1 eud_c2 ewg if neg ==1, lc(red) lp(dash) hor) ///
(scatter ewg           eud if neg ==1, mlabel(p) mlabcolor(red) mcolor(red) mlabsize(vsmall) mlabposition(8) msize(small)) ///
, leg(off) xline(0, lc(gs10)) yline(0, lc(gs10)) graphregion(fcolor(white)) xt("Marginal effect on non-enmployment duration") yt("Marginal effect on wages") ///
 name(F4a, replace)
graph export "$figs/litfigure.pdf", replace
	
}
********************************************************************************
* Figure A10 - inflows
********************************************************************************
{

* data
use "$data/int/analysis_dataset_spell.dta", clear

* dates
scalar ref = mdy(7,15,2012)
scalar t1 = mdy(7,14,2011)
scalar t1b = mdy(7,14,2012)
scalar t2 = mdy(7,15,2012)
scalar t2b = mdy(7,15,2013)

* keep relevant individuals
keep if state==2 & prevstate==1
keep if (age>52 & age<=58)
drop if age==.

keep if (u_entry_date >=t1 & u_entry_date <t1b ) | (u_entry_date >=t2 & u_entry_date <t2b )
g after = (u_entry_date >=t2 & u_entry_date <t2b )

* kernel density
#d;
	tw (kdensity age if after ==0, lp(solid) lcolor(blue) lw(medthick))
	(kdensity age if after ==1, lp(dash) lcolor(red) lw(medthick)),
	xtitle("Age at UI entry", size(small)) 
	ytitle("Density", size(small))
	xlabel(52(1)58, labsize(small))
	ylabel(, labsize(small)) 
	legend(off)
	graphregion(color(white)) bgcolor(white)
	;
#d cr
graph export "$figs/rev_UIinflowage_kdens.pdf", replace

* ks test
ksmirnov age, by(after)

* cdf
#d;
	cdfplot age, by(after)
	opt1(lc(blue red) lp(solid dash) lw(medthick medthick))
	xtitle("Age at UI entry", size(small)) 
	ytitle("Cumulative Density", size(small)) 
	xsc(range(52,58)) 
	xlabel(52(1)58, labsize(small)) 
	ylabel(, labsize(small))
	legend(label(1 "Before") label(2 "After") size(small))
	graphregion(color(white)) bgcolor(white)
;
#d cr
graph export "$figs/rev_UIinflowage_cdf.pdf", replace
	
}
********************************************************************************
* closing
********************************************************************************
{
		
cap erase "$data/temp/temp_contributionjul2013.dta"	
cap erase "$data/temp/temp_workedjul.dta"
cap erase "$data/temp/analysis_dataset_hazards.dta"
cap erase "$data/temp/donut_robustness.dta"
	
clear
cap log close
}
